#include "texture.h"

#include <glad/glad.h>
#include <glm/glm.hpp>

#include <string>
#include <iostream>

#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>

Texture::Texture() : id(0) {}
Texture::~Texture() { free(); }

bool Texture::loadPath(const GLchar *path) {
  id = loadTexture(path);
  return isOK();
}
GLuint Texture::loadTexture(const GLchar *path) {
  int width, height, nrComponents;
  unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
  if (!data) {
    std::cerr << "[TEXTURE] failed to load at path: " << path << std::endl;
    return 0;
  }

  GLuint textureID = 0;
  glGenTextures(1, &textureID);
  if (textureID == 0) {
    stbi_image_free(data);
    std::cerr << "[TEXTURE] error glGenTextures at path: " << path << std::endl;
    return 0;
  }

  GLenum format;
  if (nrComponents == 1)
    format = GL_RED;
  else if (nrComponents == 3)
    format = GL_RGB;
  else if (nrComponents == 4)
    format = GL_RGBA;

  glBindTexture(GL_TEXTURE_2D, textureID);
  glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
  glGenerateMipmap(GL_TEXTURE_2D);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  stbi_image_free(data);

  return textureID;
}
